package examples;

public class TwoPhaseTermination{
    private Thread monitor;


    public static void main(String[] args) throws InterruptedException {
        TwoPhaseTermination twoPhaseTermination = new TwoPhaseTermination();
        twoPhaseTermination.start();

        Thread.sleep(3500);
        twoPhaseTermination.stop();
    }

    public void start(){
        if(monitor == null){
            monitor = new Thread(()->{
                while(true){
                    // 正常打断
                    if(Thread.currentThread().isInterrupted()){
                        // 释放资源等后续操作
                        break;
                    }
                    try {
                        // sleep会清除打断标记
                        Thread.sleep(1000);
                        System.out.println("监控信息");
                    } catch (InterruptedException e) {
                        // 打断标记设置为true
                        Thread.currentThread().interrupt();
                    }
                }
            }, "m-thread");
        }

        monitor.start();
    }

    public void stop(){
        monitor.interrupt();
    }
}
